import { createRouter, createWebHistory } from 'vue-router'
import { useUserStore } from '@/stores'

const routes = [
	{
		path: '/',
		redirect: '/image-to-video',
		component: () => import('@/views/Layout.vue'),
		children: [
			{
				path: '/image-to-video',
				name: '文生视频',
				component: () => import('@/views/ImageToVideo/index.vue'),
			},
		],
	},
	{
		path: '/:pathMatch(.*)*',
		redirect: '/',
	},
]

const router = createRouter({
	history: createWebHistory(import.meta.env.BASE_URL),
	routes,
})

router.afterEach((to, from) => {
	if (
		to.path === '/image-to-video' &&
		to.query.access_token &&
		to.query.refresh_token
	) {
		const accessToken = to.query.access_token
		const refreshToken = to.query.refresh_token

		localStorage.setItem('token', accessToken)
		localStorage.setItem('refresh_token', refreshToken)

		router.replace('/')
		useUserStore().getUserInfo()
	}
})

export default router
